acda5d655a27c451a81adad5d7a6c2e73a94a2d6
2 * Base library for MediaWiki.
5 * @alternateClassName mediaWiki
9 var mw
= ( function ( $, undefined ) {
14 var hasOwn
= Object
.prototype.hasOwnProperty
,
15 slice
= Array
.prototype.slice
;
18 * Log a message to window.console, if possible. Useful to force logging of some
19 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
20 * Gets console references in each invocation, so that delayed debugging tools work
21 * fine. No need for optimization here, which would only result in losing logs.
24 * @param {string} msg text for the log entry.
27 function log( msg
, e
) {
28 var console
= window
.console
;
29 if ( console
&& console
.log
) {
31 // If we have an exception object, log it through .error() to trigger
32 // proper stacktraces in browsers that support it. There are no (known)
33 // browsers that don't support .error(), that do support .log() and
34 // have useful exception handling through .log().
35 if ( e
&& console
.error
) {
36 console
.error( String( e
), e
);
41 /* Object constructors */
44 * Creates an object that can be read from or written to from prototype functions
45 * that allow both single and multiple variables at once.
49 * var addies, wanted, results;
51 * // Create your address book
52 * addies = new mw.Map();
54 * // This data could be coming from an external source (eg. API/AJAX)
56 * 'John Doe' : '10 Wall Street, New York, USA',
57 * 'Jane Jackson' : '21 Oxford St, London, UK',
58 * 'Dominique van Halen' : 'Kalverstraat 7, Amsterdam, NL'
61 * wanted = ['Dominique van Halen', 'George Johnson', 'Jane Jackson'];
63 * // You can detect missing keys first
64 * if ( !addies.exists( wanted ) ) {
65 * // One or more are missing (in this case: "George Johnson")
66 * mw.log( 'One or more names were not found in your address book' );
69 * // Or just let it give you what it can
70 * results = addies.get( wanted, 'Middle of Nowhere, Alaska, US' );
71 * mw.log( results['Jane Jackson'] ); // "21 Oxford St, London, UK"
72 * mw.log( results['George Johnson'] ); // "Middle of Nowhere, Alaska, US"
77 * @param {boolean} [global=false] Whether to store the values in the global window
78 * object or a exclusively in the object property 'values'.
80 function Map( global
) {
81 this.values
= global
=== true ? window
: {};
87 * Get the value of one or multiple a keys.
89 * If called with no arguments, all values will be returned.
91 * @param {string|Array} selection String key or array of keys to get values for.
92 * @param {Mixed} [fallback] Value to use in case key(s) do not exist.
93 * @return mixed If selection was a string returns the value or null,
94 * If selection was an array, returns an object of key/values (value is null if not found),
95 * If selection was not passed or invalid, will return the 'values' object member (be careful as
96 * objects are always passed by reference in JavaScript!).
97 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
99 get: function ( selection
, fallback
) {
101 // If we only do this in the `return` block, it'll fail for the
102 // call to get() from the mutli-selection block.
103 fallback
= arguments
.length
> 1 ? fallback
: null;
105 if ( $.isArray( selection
) ) {
106 selection
= slice
.call( selection
);
108 for ( i
= 0; i
< selection
.length
; i
++ ) {
109 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
114 if ( typeof selection
=== 'string' ) {
115 if ( !hasOwn
.call( this.values
, selection
) ) {
118 return this.values
[selection
];
121 if ( selection
=== undefined ) {
125 // invalid selection key
130 * Sets one or multiple key/value pairs.
132 * @param {string|Object} selection String key to set value for, or object mapping keys to values.
133 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
134 * @return {Boolean} This returns true on success, false on failure.
136 set: function ( selection
, value
) {
139 if ( $.isPlainObject( selection
) ) {
140 for ( s
in selection
) {
141 this.values
[s
] = selection
[s
];
145 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
146 this.values
[selection
] = value
;
153 * Checks if one or multiple keys exist.
155 * @param {Mixed} selection String key or array of keys to check
156 * @return {boolean} Existence of key(s)
158 exists: function ( selection
) {
161 if ( $.isArray( selection
) ) {
162 for ( s
= 0; s
< selection
.length
; s
++ ) {
163 if ( typeof selection
[s
] !== 'string' || !hasOwn
.call( this.values
, selection
[s
] ) ) {
169 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
174 * Object constructor for messages.
176 * Similar to the Message class in MediaWiki PHP.
178 * Format defaults to 'text'.
183 * @param {mw.Map} map Message storage
184 * @param {string} key
185 * @param {Array} [parameters]
187 function Message( map
, key
, parameters
) {
188 this.format
= 'text';
191 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
195 Message
.prototype = {
197 * Simple message parser, does $N replacement and nothing else.
199 * This may be overridden to provide a more complex message parser.
201 * The primary override is in mediawiki.jqueryMsg.
203 * This function will not be called for nonexistent messages.
205 parser: function () {
206 var parameters
= this.parameters
;
207 return this.map
.get( this.key
).replace( /\$(\d+)/g, function ( str
, match
) {
208 var index
= parseInt( match
, 10 ) - 1;
209 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
214 * Appends (does not replace) parameters for replacement to the .parameters property.
216 * @param {Array} parameters
219 params: function ( parameters
) {
221 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
222 this.parameters
.push( parameters
[i
] );
228 * Converts message object to its string form based on the state of format.
230 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
232 toString: function () {
235 if ( !this.exists() ) {
236 // Use <key> as text if key does not exist
237 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
238 // format 'escaped' and 'parse' need to have the brackets and key html escaped
239 return mw
.html
.escape( '<' + this.key
+ '>' );
241 return '<' + this.key
+ '>';
244 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
245 text
= this.parser();
248 if ( this.format
=== 'escaped' ) {
249 text
= this.parser();
250 text
= mw
.html
.escape( text
);
257 * Changes format to 'parse' and converts message to string
259 * If jqueryMsg is loaded, this parses the message text from wikitext
260 * (where supported) to HTML
262 * Otherwise, it is equivalent to plain.
264 * @return {string} String form of parsed message
267 this.format
= 'parse';
268 return this.toString();
272 * Changes format to 'plain' and converts message to string
274 * This substitutes parameters, but otherwise does not change the
277 * @return {string} String form of plain message
280 this.format
= 'plain';
281 return this.toString();
285 * Changes format to 'text' and converts message to string
287 * If jqueryMsg is loaded, {{-transformation is done where supported
288 * (such as {{plural:}}, {{gender:}}, {{int:}}).
290 * Otherwise, it is equivalent to plain.
293 this.format
= 'text';
294 return this.toString();
298 * Changes the format to 'escaped' and converts message to string
300 * This is equivalent to using the 'text' format (see text method), then
301 * HTML-escaping the output.
303 * @return {string} String form of html escaped message
305 escaped: function () {
306 this.format
= 'escaped';
307 return this.toString();
311 * Checks if message exists
316 exists: function () {
317 return this.map
.exists( this.key
);
325 * Dummy placeholder for {@link mw.log}
329 var log = function () {};
330 log
.warn = function () {};
331 log
.deprecate = function ( obj
, key
, val
) {
337 // Make the Map constructor publicly available.
340 // Make the Message constructor publicly available.
344 * Map of configuration values
346 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
349 * If `$wgLegacyJavaScriptGlobals` is true, this Map will put its values in the
350 * global window object.
352 * @property {mw.Map} config
354 // Dummy placeholder. Re-assigned in ResourceLoaderStartupModule with an instance of `mw.Map`.
358 * Empty object that plugins can be installed in.
364 * Access container for deprecated functionality that can be moved from
365 * from their legacy location and attached to this object (e.g. a global
366 * function that is deprecated and as stop-gap can be exposed through here).
368 * This was reserved for future use but never ended up being used.
370 * @deprecated since 1.22: Let deprecated identifiers keep their original name
371 * and use mw.log#deprecate to create an access container for tracking.
377 * Localization system
385 * Get a message object.
387 * Similar to wfMessage() in MediaWiki PHP.
389 * @param {string} key Key of message to get
390 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
391 * @return {mw.Message}
393 message: function ( key
) {
394 // Variadic arguments
395 var parameters
= slice
.call( arguments
, 1 );
396 return new Message( mw
.messages
, key
, parameters
);
400 * Get a message string using 'text' format.
402 * Similar to wfMsg() in MediaWiki PHP.
405 * @param {string} key Key of message to get
406 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
410 return mw
.message
.apply( mw
.message
, arguments
).toString();
414 * Client-side module loader which integrates with the MediaWiki ResourceLoader
418 loader
: ( function () {
420 /* Private Members */
423 * Mapping of registered modules
425 * The jquery module is pre-registered, because it must have already
426 * been provided for this object to have been built, and in debug mode
427 * jquery would have been provided through a unique loader request,
428 * making it impossible to hold back registration of jquery until after
431 * For exact details on support for script, style and messages, look at
432 * mw.loader.implement.
437 * 'version': ############## (unix timestamp),
438 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
439 * 'group': 'somegroup', (or) null,
440 * 'source': 'local', 'someforeignwiki', (or) null
441 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error' or 'missing'
444 * 'messages': { 'key': 'value' },
453 // Mapping of sources, keyed by source-id, values are objects.
457 // 'loadScript': 'http://foo.bar/w/load.php'
462 // List of modules which will be loaded as when ready
464 // List of modules to be loaded
466 // List of callback functions waiting for modules to be ready to be called
468 // Selector cache for the marker element. Use getMarker() to get/use the marker!
470 // Buffer for addEmbeddedCSS.
472 // Callbacks for addEmbeddedCSS.
473 cssCallbacks
= $.Callbacks();
475 /* Private methods */
477 function getMarker() {
483 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
484 if ( $marker
.length
) {
487 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
488 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
494 * Create a new style tag and add it to the DOM.
497 * @param {string} text CSS text
498 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag should be
499 * inserted before. Otherwise it will be appended to `<head>`.
500 * @return {HTMLElement} Reference to the created `<style>` element.
502 function newStyleTag( text
, nextnode
) {
503 var s
= document
.createElement( 'style' );
504 // Insert into document before setting cssText (bug 33305)
506 // Must be inserted with native insertBefore, not $.fn.before.
507 // When using jQuery to insert it, like $nextnode.before( s ),
508 // then IE6 will throw "Access is denied" when trying to append
509 // to .cssText later. Some kind of weird security measure.
510 // http://stackoverflow.com/q/12586482/319266
511 // Works: jsfiddle.net/zJzMy/1
512 // Fails: jsfiddle.net/uJTQz
513 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
514 if ( nextnode
.jquery
) {
515 nextnode
= nextnode
.get( 0 );
517 nextnode
.parentNode
.insertBefore( s
, nextnode
);
519 document
.getElementsByTagName( 'head' )[0].appendChild( s
);
521 if ( s
.styleSheet
) {
523 s
.styleSheet
.cssText
= text
;
526 // (Safari sometimes borks on non-string values,
527 // play safe by casting to a string, just in case.)
528 s
.appendChild( document
.createTextNode( String( text
) ) );
534 * Checks whether it is safe to add this css to a stylesheet.
537 * @param {string} cssText
538 * @return {boolean} False if a new one must be created.
540 function canExpandStylesheetWith( cssText
) {
541 // Makes sure that cssText containing `@import`
542 // rules will end up in a new stylesheet (as those only work when
543 // placed at the start of a stylesheet; bug 35562).
544 return cssText
.indexOf( '@import' ) === -1;
548 * Add a bit of CSS text to the current browser page.
550 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
551 * or create a new one based on whether the given `cssText` is safe for extension.
553 * @param {string} [cssText=cssBuffer] If called without cssText,
554 * the internal buffer will be inserted instead.
555 * @param {Function} [callback]
557 function addEmbeddedCSS( cssText
, callback
) {
561 cssCallbacks
.add( callback
);
564 // Yield once before inserting the <style> tag. There are likely
565 // more calls coming up which we can combine this way.
566 // Appending a stylesheet and waiting for the browser to repaint
567 // is fairly expensive, this reduces it (bug 45810)
569 // Be careful not to extend the buffer with css that needs a new stylesheet
570 if ( !cssBuffer
|| canExpandStylesheetWith( cssText
) ) {
571 // Linebreak for somewhat distinguishable sections
572 // (the rl-cachekey comment separating each)
573 cssBuffer
+= '\n' + cssText
;
574 // TODO: Use requestAnimationFrame in the future which will
575 // perform even better by not injecting styles while the browser
577 setTimeout( function () {
578 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
579 // (below version 13) has the non-standard behaviour of passing a
580 // numerical "lateness" value as first argument to this callback
581 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
587 // This is a delayed call and we got a buffer still
588 } else if ( cssBuffer
) {
592 // This is a delayed call, but buffer is already cleared by
593 // another delayed call.
597 // By default, always create a new <style>. Appending text
598 // to a <style> tag means the contents have to be re-parsed (bug 45810).
599 // Except, of course, in IE below 9, in there we default to
600 // re-using and appending to a <style> tag due to the
601 // IE stylesheet limit (bug 31676).
602 if ( 'documentMode' in document
&& document
.documentMode
<= 9 ) {
604 $style
= getMarker().prev();
605 // Verify that the the element before Marker actually is a
606 // <style> tag and one that came from ResourceLoader
607 // (not some other style tag or even a `<meta>` or `<script>`).
608 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
609 // There's already a dynamic <style> tag present and
610 // canExpandStylesheetWith() gave a green light to append more to it.
611 styleEl
= $style
.get( 0 );
612 if ( styleEl
.styleSheet
) {
614 styleEl
.styleSheet
.cssText
+= cssText
; // IE
616 log( 'addEmbeddedCSS fail', e
);
619 styleEl
.appendChild( document
.createTextNode( String( cssText
) ) );
621 cssCallbacks
.fire().empty();
626 $( newStyleTag( cssText
, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
628 cssCallbacks
.fire().empty();
632 * Generates an ISO8601 "basic" string from a UNIX timestamp
635 function formatVersionNumber( timestamp
) {
637 function pad( a
, b
, c
) {
638 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
640 d
.setTime( timestamp
* 1000 );
642 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
643 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
648 * Resolves dependencies and detects circular references.
651 * @param {string} module Name of the top-level module whose dependencies shall be
652 * resolved and sorted.
653 * @param {Array} resolved Returns a topological sort of the given module and its
654 * dependencies, such that later modules depend on earlier modules. The array
655 * contains the module names. If the array contains already some module names,
656 * this function appends its result to the pre-existing array.
657 * @param {Object} [unresolved] Hash used to track the current dependency
658 * chain; used to report loops in the dependency graph.
659 * @throws {Error} If any unregistered module or a dependency loop is encountered
661 function sortDependencies( module
, resolved
, unresolved
) {
664 if ( registry
[module
] === undefined ) {
665 throw new Error( 'Unknown dependency: ' + module
);
667 // Resolves dynamic loader function and replaces it with its own results
668 if ( $.isFunction( registry
[module
].dependencies
) ) {
669 registry
[module
].dependencies
= registry
[module
].dependencies();
670 // Ensures the module's dependencies are always in an array
671 if ( typeof registry
[module
].dependencies
!== 'object' ) {
672 registry
[module
].dependencies
= [registry
[module
].dependencies
];
675 if ( $.inArray( module
, resolved
) !== -1 ) {
676 // Module already resolved; nothing to do.
679 // unresolved is optional, supply it if not passed in
683 // Tracks down dependencies
684 deps
= registry
[module
].dependencies
;
686 for ( n
= 0; n
< len
; n
+= 1 ) {
687 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
688 if ( unresolved
[deps
[n
]] ) {
690 'Circular reference detected: ' + module
+
696 unresolved
[module
] = true;
697 sortDependencies( deps
[n
], resolved
, unresolved
);
698 delete unresolved
[module
];
701 resolved
[resolved
.length
] = module
;
705 * Gets a list of module names that a module depends on in their proper dependency
709 * @param {string} module Module name or array of string module names
710 * @return {Array} list of dependencies, including 'module'.
711 * @throws {Error} If circular reference is detected
713 function resolve( module
) {
716 // Allow calling with an array of module names
717 if ( $.isArray( module
) ) {
719 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
720 sortDependencies( module
[m
], resolved
);
725 if ( typeof module
=== 'string' ) {
727 sortDependencies( module
, resolved
);
731 throw new Error( 'Invalid module argument: ' + module
);
735 * Narrows a list of module names down to those matching a specific
736 * state (see comment on top of this scope for a list of valid states).
737 * One can also filter for 'unregistered', which will return the
738 * modules names that don't have a registry entry.
741 * @param {string|string[]} states Module states to filter by
742 * @param {Array} [modules] List of module names to filter (optional, by default the entire
744 * @return {Array} List of filtered module names
746 function filter( states
, modules
) {
747 var list
, module
, s
, m
;
749 // Allow states to be given as a string
750 if ( typeof states
=== 'string' ) {
753 // If called without a list of modules, build and use a list of all modules
755 if ( modules
=== undefined ) {
757 for ( module
in registry
) {
758 modules
[modules
.length
] = module
;
761 // Build a list of modules which are in one of the specified states
762 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
763 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
764 if ( registry
[modules
[m
]] === undefined ) {
765 // Module does not exist
766 if ( states
[s
] === 'unregistered' ) {
768 list
[list
.length
] = modules
[m
];
771 // Module exists, check state
772 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
774 list
[list
.length
] = modules
[m
];
783 * Determine whether all dependencies are in state 'ready', which means we may
784 * execute the module or job now.
787 * @param {Array} dependencies Dependencies (module names) to be checked.
788 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
790 function allReady( dependencies
) {
791 return filter( 'ready', dependencies
).length
=== dependencies
.length
;
795 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
796 * and modules that depend upon this module. if the given module failed, propagate the 'error'
797 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
798 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
801 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
803 function handlePending( module
) {
804 var j
, job
, hasErrors
, m
, stateChange
;
807 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) !== -1 ) {
808 // If the current module failed, mark all dependent modules also as failed.
809 // Iterate until steady-state to propagate the error state upwards in the
813 for ( m
in registry
) {
814 if ( $.inArray( registry
[m
].state
, ['error', 'missing'] ) === -1 ) {
815 if ( filter( ['error', 'missing'], registry
[m
].dependencies
).length
> 0 ) {
816 registry
[m
].state
= 'error';
821 } while ( stateChange
);
824 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
825 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
826 hasErrors
= filter( ['error', 'missing'], jobs
[j
].dependencies
).length
> 0;
827 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
828 // All dependencies satisfied, or some have errors
834 if ( $.isFunction( job
.error
) ) {
835 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [module
] );
838 if ( $.isFunction( job
.ready
) ) {
843 // A user-defined callback raised an exception.
844 // Swallow it to protect our state machine!
845 log( 'Exception thrown by job.error', e
);
850 if ( registry
[module
].state
=== 'ready' ) {
851 // The current module became 'ready'. Set it in the module store, and recursively execute all
852 // dependent modules that are loaded and now have all dependencies satisfied.
853 mw
.loader
.store
.set( module
, registry
[module
] );
854 for ( m
in registry
) {
855 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
863 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
864 * depending on whether document-ready has occurred yet and whether we are in async mode.
867 * @param {string} src URL to script, will be used as the src attribute in the script tag
868 * @param {Function} [callback] Callback which will be run when the script is done
870 function addScript( src
, callback
, async
) {
871 /*jshint evil:true */
872 var script
, head
, done
;
874 // Using isReady directly instead of storing it locally from
875 // a $.fn.ready callback (bug 31895).
876 if ( $.isReady
|| async
) {
877 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
878 // it uses XHR and eval for same-domain scripts, which we don't want because it
879 // messes up line numbers.
880 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
882 // IE-safe way of getting the <head>. document.head isn't supported
883 // in old IE, and doesn't work when in the <head>.
885 head
= document
.getElementsByTagName( 'head' )[0] || document
.body
;
887 script
= document
.createElement( 'script' );
890 if ( $.isFunction( callback
) ) {
891 script
.onload
= script
.onreadystatechange = function () {
896 || /loaded|complete/.test( script
.readyState
)
901 // Handle memory leak in IE
902 script
.onload
= script
.onreadystatechange
= null;
904 // Detach the element from the document
905 if ( script
.parentNode
) {
906 script
.parentNode
.removeChild( script
);
909 // Dereference the element from javascript
917 if ( window
.opera
) {
918 // Appending to the <head> blocks rendering completely in Opera,
919 // so append to the <body> after document ready. This means the
920 // scripts only start loading after the document has been rendered,
921 // but so be it. Opera users don't deserve faster web pages if their
922 // browser makes it impossible.
924 document
.body
.appendChild( script
);
927 head
.appendChild( script
);
930 document
.write( mw
.html
.element( 'script', { 'src': src
}, '' ) );
931 if ( $.isFunction( callback
) ) {
932 // Document.write is synchronous, so this is called when it's done
933 // FIXME: that's a lie. doc.write isn't actually synchronous
940 * Executes a loaded module, making it ready to use
943 * @param {string} module Module name to execute
945 function execute( module
) {
946 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
,
947 cssHandlesRegistered
= false;
949 if ( registry
[module
] === undefined ) {
950 throw new Error( 'Module has not been registered yet: ' + module
);
951 } else if ( registry
[module
].state
=== 'registered' ) {
952 throw new Error( 'Module has not been requested from the server yet: ' + module
);
953 } else if ( registry
[module
].state
=== 'loading' ) {
954 throw new Error( 'Module has not completed loading yet: ' + module
);
955 } else if ( registry
[module
].state
=== 'ready' ) {
956 throw new Error( 'Module has already been executed: ' + module
);
960 * Define loop-function here for efficiency
961 * and to avoid re-using badly scoped variables.
964 function addLink( media
, url
) {
965 var el
= document
.createElement( 'link' );
966 getMarker().before( el
); // IE: Insert in dom before setting href
967 el
.rel
= 'stylesheet';
968 if ( media
&& media
!== 'all' ) {
974 function runScript() {
975 var script
, markModuleReady
, nestedAddScript
;
977 script
= registry
[module
].script
;
978 markModuleReady = function () {
979 registry
[module
].state
= 'ready';
980 handlePending( module
);
982 nestedAddScript = function ( arr
, callback
, async
, i
) {
983 // Recursively call addScript() in its own callback
984 // for each element of arr.
985 if ( i
>= arr
.length
) {
986 // We're at the end of the array
991 addScript( arr
[i
], function () {
992 nestedAddScript( arr
, callback
, async
, i
+ 1 );
996 if ( $.isArray( script
) ) {
997 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
998 } else if ( $.isFunction( script
) ) {
999 registry
[module
].state
= 'ready';
1001 handlePending( module
);
1004 // This needs to NOT use mw.log because these errors are common in production mode
1005 // and not in debug mode, such as when a symbol that should be global isn't exported
1006 log( 'Exception thrown by ' + module
, e
);
1007 registry
[module
].state
= 'error';
1008 handlePending( module
);
1012 // This used to be inside runScript, but since that is now fired asychronously
1013 // (after CSS is loaded) we need to set it here right away. It is crucial that
1014 // when execute() is called this is set synchronously, otherwise modules will get
1015 // executed multiple times as the registry will state that it isn't loading yet.
1016 registry
[module
].state
= 'loading';
1018 // Add localizations to message system
1019 if ( $.isPlainObject( registry
[module
].messages
) ) {
1020 mw
.messages
.set( registry
[module
].messages
);
1023 if ( $.isReady
|| registry
[module
].async
) {
1024 // Make sure we don't run the scripts until all (potentially asynchronous)
1025 // stylesheet insertions have completed.
1028 checkCssHandles = function () {
1029 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1030 // one of the cssHandles is fired while we're still creating more handles.
1031 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1033 runScript
= undefined; // Revoke
1036 cssHandle = function () {
1037 var check
= checkCssHandles
;
1039 return function () {
1043 check
= undefined; // Revoke
1049 // We are in blocking mode, and so we can't afford to wait for CSS
1050 cssHandle = function () {};
1052 checkCssHandles
= runScript
;
1055 // Process styles (see also mw.loader.implement)
1056 // * back-compat: { <media>: css }
1057 // * back-compat: { <media>: [url, ..] }
1058 // * { "css": [css, ..] }
1059 // * { "url": { <media>: [url, ..] } }
1060 if ( $.isPlainObject( registry
[module
].style
) ) {
1061 for ( key
in registry
[module
].style
) {
1062 value
= registry
[module
].style
[key
];
1065 if ( key
!== 'url' && key
!== 'css' ) {
1066 // Backwards compatibility, key is a media-type
1067 if ( typeof value
=== 'string' ) {
1068 // back-compat: { <media>: css }
1069 // Ignore 'media' because it isn't supported (nor was it used).
1070 // Strings are pre-wrapped in "@media". The media-type was just ""
1071 // (because it had to be set to something).
1072 // This is one of the reasons why this format is no longer used.
1073 addEmbeddedCSS( value
, cssHandle() );
1075 // back-compat: { <media>: [url, ..] }
1081 // Array of css strings in key 'css',
1082 // or back-compat array of urls from media-type
1083 if ( $.isArray( value
) ) {
1084 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
1085 if ( key
=== 'bc-url' ) {
1086 // back-compat: { <media>: [url, ..] }
1087 addLink( media
, value
[i
] );
1088 } else if ( key
=== 'css' ) {
1089 // { "css": [css, ..] }
1090 addEmbeddedCSS( value
[i
], cssHandle() );
1093 // Not an array, but a regular object
1094 // Array of urls inside media-type key
1095 } else if ( typeof value
=== 'object' ) {
1096 // { "url": { <media>: [url, ..] } }
1097 for ( media
in value
) {
1098 urls
= value
[media
];
1099 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
1100 addLink( media
, urls
[i
] );
1108 cssHandlesRegistered
= true;
1113 * Adds a dependencies to the queue with optional callbacks to be run
1114 * when the dependencies are ready or fail
1117 * @param {string|string[]} dependencies Module name or array of string module names
1118 * @param {Function} [ready] Callback to execute when all dependencies are ready
1119 * @param {Function} [error] Callback to execute when any dependency fails
1120 * @param {boolean} [async] If true, load modules asynchronously even if
1121 * document ready has not yet occurred.
1123 function request( dependencies
, ready
, error
, async
) {
1126 // Allow calling by single module name
1127 if ( typeof dependencies
=== 'string' ) {
1128 dependencies
= [dependencies
];
1131 // Add ready and error callbacks if they were given
1132 if ( ready
!== undefined || error
!== undefined ) {
1133 jobs
[jobs
.length
] = {
1134 'dependencies': filter(
1135 ['registered', 'loading', 'loaded'],
1143 // Queue up any dependencies that are registered
1144 dependencies
= filter( ['registered'], dependencies
);
1145 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
1146 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
1147 queue
[queue
.length
] = dependencies
[n
];
1149 // Mark this module as async in the registry
1150 registry
[dependencies
[n
]].async
= true;
1159 function sortQuery(o
) {
1160 var sorted
= {}, key
, a
= [];
1162 if ( hasOwn
.call( o
, key
) ) {
1167 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
1168 sorted
[a
[key
]] = o
[a
[key
]];
1174 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1175 * to a query string of the form foo.bar,baz|bar.baz,quux
1178 function buildModulesString( moduleMap
) {
1179 var arr
= [], p
, prefix
;
1180 for ( prefix
in moduleMap
) {
1181 p
= prefix
=== '' ? '' : prefix
+ '.';
1182 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
1184 return arr
.join( '|' );
1188 * Asynchronously append a script tag to the end of the body
1189 * that invokes load.php
1191 * @param {Object} moduleMap Module map, see #buildModulesString
1192 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1193 * @param {string} sourceLoadScript URL of load.php
1194 * @param {boolean} async If true, use an asynchronous request even if document ready has not yet occurred
1196 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
1197 var request
= $.extend(
1198 { modules
: buildModulesString( moduleMap
) },
1201 request
= sortQuery( request
);
1202 // Asynchronously append a script tag to the end of the body
1203 // Append &* to avoid triggering the IE6 extension check
1204 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
1207 /* Public Members */
1210 * The module registry is exposed as an aid for debugging and inspecting page
1211 * state; it is not a public interface for modifying the registry.
1217 moduleRegistry
: registry
,
1220 * @inheritdoc #newStyleTag
1223 addStyleTag
: newStyleTag
,
1226 * Batch-request queued dependencies from the server.
1229 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1230 source
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
1231 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1232 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
1234 // Build a list of request parameters common to all requests.
1236 skin
: mw
.config
.get( 'skin' ),
1237 lang
: mw
.config
.get( 'wgUserLanguage' ),
1238 debug
: mw
.config
.get( 'debug' )
1240 // Split module batch by source and by group.
1242 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
1244 // Appends a list of modules from the queue to the batch
1245 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1246 // Only request modules which are registered
1247 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
1248 // Prevent duplicate entries
1249 if ( $.inArray( queue
[q
], batch
) === -1 ) {
1250 batch
[batch
.length
] = queue
[q
];
1251 // Mark registered modules as loading
1252 registry
[queue
[q
]].state
= 'loading';
1257 mw
.loader
.store
.init();
1258 if ( mw
.loader
.store
.enabled
) {
1259 batch
= $.grep( batch
, function ( module
) {
1260 var source
= mw
.loader
.store
.get( module
);
1262 $.globalEval( source
);
1263 return false; // Don't fetch
1265 return true; // Fetch
1269 // Early exit if there's nothing to load...
1270 if ( !batch
.length
) {
1274 // The queue has been processed into the batch, clear up the queue.
1277 // Always order modules alphabetically to help reduce cache
1278 // misses for otherwise identical content.
1281 // Split batch by source and by group.
1282 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1283 bSource
= registry
[batch
[b
]].source
;
1284 bGroup
= registry
[batch
[b
]].group
;
1285 if ( splits
[bSource
] === undefined ) {
1286 splits
[bSource
] = {};
1288 if ( splits
[bSource
][bGroup
] === undefined ) {
1289 splits
[bSource
][bGroup
] = [];
1291 bSourceGroup
= splits
[bSource
][bGroup
];
1292 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1295 // Clear the batch - this MUST happen before we append any
1296 // script elements to the body or it's possible that a script
1297 // will be locally cached, instantly load, and work the batch
1298 // again, all before we've cleared it causing each request to
1299 // include modules which are already loaded.
1302 for ( source
in splits
) {
1304 sourceLoadScript
= sources
[source
].loadScript
;
1306 for ( group
in splits
[source
] ) {
1308 // Cache access to currently selected list of
1309 // modules for this group from this source.
1310 modules
= splits
[source
][group
];
1312 // Calculate the highest timestamp
1314 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
1315 if ( registry
[modules
[g
]].version
> maxVersion
) {
1316 maxVersion
= registry
[modules
[g
]].version
;
1320 currReqBase
= $.extend( { version
: formatVersionNumber( maxVersion
) }, reqBase
);
1321 // For user modules append a user name to the request.
1322 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1323 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1325 currReqBaseLength
= $.param( currReqBase
).length
;
1327 // We may need to split up the request to honor the query string length limit,
1328 // so build it piece by piece.
1329 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1331 moduleMap
= {}; // { prefix: [ suffixes ] }
1333 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1334 // Determine how many bytes this module would add to the query string
1335 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1336 // Note that these substr() calls work even if lastDotIndex == -1
1337 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1338 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
1339 bytesAdded
= moduleMap
[prefix
] !== undefined
1340 ? suffix
.length
+ 3 // '%2C'.length == 3
1341 : modules
[i
].length
+ 3; // '%7C'.length == 3
1343 // If the request would become too long, create a new one,
1344 // but don't create empty requests
1345 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1346 // This request would become too long, create a new one
1347 // and fire off the old one
1348 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1351 l
= currReqBaseLength
+ 9;
1353 if ( moduleMap
[prefix
] === undefined ) {
1354 moduleMap
[prefix
] = [];
1356 moduleMap
[prefix
].push( suffix
);
1357 if ( !registry
[modules
[i
]].async
) {
1358 // If this module is blocking, make the entire request blocking
1359 // This is slightly suboptimal, but in practice mixing of blocking
1360 // and async modules will only occur in debug mode.
1365 // If there's anything left in moduleMap, request that too
1366 if ( !$.isEmptyObject( moduleMap
) ) {
1367 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1374 * Register a source.
1376 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1377 * @param {Object} props Object containing only the loadScript property which is a url to
1378 * the load.php location of the source.
1381 addSource: function ( id
, props
) {
1383 // Allow multiple additions
1384 if ( typeof id
=== 'object' ) {
1385 for ( source
in id
) {
1386 mw
.loader
.addSource( source
, id
[source
] );
1391 if ( sources
[id
] !== undefined ) {
1392 throw new Error( 'source already registered: ' + id
);
1395 sources
[id
] = props
;
1401 * Register a module, letting the system know about it and its
1402 * properties. Startup modules contain calls to this function.
1404 * @param {string} module Module name
1405 * @param {number} version Module version number as a timestamp (falls backs to 0)
1406 * @param {string|Array|Function} dependencies One string or array of strings of module
1407 * names on which this module depends, or a function that returns that array.
1408 * @param {string} [group=null] Group which the module is in
1409 * @param {string} [source='local'] Name of the source
1411 register: function ( module
, version
, dependencies
, group
, source
) {
1413 // Allow multiple registration
1414 if ( typeof module
=== 'object' ) {
1415 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
1416 // module is an array of module names
1417 if ( typeof module
[m
] === 'string' ) {
1418 mw
.loader
.register( module
[m
] );
1419 // module is an array of arrays
1420 } else if ( typeof module
[m
] === 'object' ) {
1421 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1427 if ( typeof module
!== 'string' ) {
1428 throw new Error( 'module must be a string, not a ' + typeof module
);
1430 if ( registry
[module
] !== undefined ) {
1431 throw new Error( 'module already registered: ' + module
);
1433 // List the module as registered
1434 registry
[module
] = {
1435 version
: version
!== undefined ? parseInt( version
, 10 ) : 0,
1437 group
: typeof group
=== 'string' ? group
: null,
1438 source
: typeof source
=== 'string' ? source
: 'local',
1441 if ( typeof dependencies
=== 'string' ) {
1442 // Allow dependencies to be given as a single module name
1443 registry
[module
].dependencies
= [ dependencies
];
1444 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1445 // Allow dependencies to be given as an array of module names
1446 // or a function which returns an array
1447 registry
[module
].dependencies
= dependencies
;
1452 * Implement a module given the components that make up the module.
1454 * When #load or #using requests one or more modules, the server
1455 * response contain calls to this function.
1457 * All arguments are required.
1459 * @param {string} module Name of module
1460 * @param {Function|Array} script Function with module code or Array of URLs to
1461 * be used as the src attribute of a new `<script>` tag.
1462 * @param {Object} style Should follow one of the following patterns:
1463 * { "css": [css, ..] }
1464 * { "url": { <media>: [url, ..] } }
1465 * And for backwards compatibility (needs to be supported forever due to caching):
1467 * { <media>: [url, ..] }
1469 * The reason css strings are not concatenated anymore is bug 31676. We now check
1470 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1472 * @param {Object} msgs List of key/value pairs to be added to {@link mw#messages}.
1474 implement: function ( module
, script
, style
, msgs
) {
1476 if ( typeof module
!== 'string' ) {
1477 throw new Error( 'module must be a string, not a ' + typeof module
);
1479 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1480 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1482 if ( !$.isPlainObject( style
) ) {
1483 throw new Error( 'style must be an object, not a ' + typeof style
);
1485 if ( !$.isPlainObject( msgs
) ) {
1486 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1488 // Automatically register module
1489 if ( registry
[module
] === undefined ) {
1490 mw
.loader
.register( module
);
1492 // Check for duplicate implementation
1493 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1494 throw new Error( 'module already implemented: ' + module
);
1496 // Attach components
1497 registry
[module
].script
= script
;
1498 registry
[module
].style
= style
;
1499 registry
[module
].messages
= msgs
;
1500 // The module may already have been marked as erroneous
1501 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1502 registry
[module
].state
= 'loaded';
1503 if ( allReady( registry
[module
].dependencies
) ) {
1510 * Execute a function as soon as one or more required modules are ready.
1512 * @param {string|Array} dependencies Module name or array of modules names the callback
1513 * dependends on to be ready before executing
1514 * @param {Function} [ready] callback to execute when all dependencies are ready
1515 * @param {Function} [error] callback to execute when if dependencies have a errors
1517 using: function ( dependencies
, ready
, error
) {
1518 var tod
= typeof dependencies
;
1520 if ( tod
!== 'object' && tod
!== 'string' ) {
1521 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1523 // Allow calling with a single dependency as a string
1524 if ( tod
=== 'string' ) {
1525 dependencies
= [ dependencies
];
1527 // Resolve entire dependency map
1528 dependencies
= resolve( dependencies
);
1529 if ( allReady( dependencies
) ) {
1530 // Run ready immediately
1531 if ( $.isFunction( ready
) ) {
1534 } else if ( filter( ['error', 'missing'], dependencies
).length
) {
1535 // Execute error immediately if any dependencies have errors
1536 if ( $.isFunction( error
) ) {
1537 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1541 // Not all dependencies are ready: queue up a request
1542 request( dependencies
, ready
, error
);
1547 * Load an external script or one or more modules.
1549 * @param {string|Array} modules Either the name of a module, array of modules,
1550 * or a URL of an external script or style
1551 * @param {string} [type='text/javascript'] mime-type to use if calling with a URL of an
1552 * external script or style; acceptable values are "text/css" and
1553 * "text/javascript"; if no type is provided, text/javascript is assumed.
1554 * @param {boolean} [async] If true, load modules asynchronously
1555 * even if document ready has not yet occurred. If false, block before
1556 * document ready and load async after. If not set, true will be
1557 * assumed if loading a URL, and false will be assumed otherwise.
1559 load: function ( modules
, type
, async
) {
1560 var filtered
, m
, module
, l
;
1563 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1564 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1566 // Allow calling with an external url or single dependency as a string
1567 if ( typeof modules
=== 'string' ) {
1568 // Support adding arbitrary external scripts
1569 if ( /^(https?:)?\/\//.test( modules
) ) {
1570 if ( async
=== undefined ) {
1571 // Assume async for bug 34542
1574 if ( type
=== 'text/css' ) {
1575 // IE7-8 throws security warnings when inserting a <link> tag
1576 // with a protocol-relative URL set though attributes (instead of
1577 // properties) - when on HTTPS. See also bug #.
1578 l
= document
.createElement( 'link' );
1579 l
.rel
= 'stylesheet';
1581 $( 'head' ).append( l
);
1584 if ( type
=== 'text/javascript' || type
=== undefined ) {
1585 addScript( modules
, null, async
);
1589 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1591 // Called with single module
1592 modules
= [ modules
];
1595 // Filter out undefined modules, otherwise resolve() will throw
1596 // an exception for trying to load an undefined module.
1597 // Undefined modules are acceptable here in load(), because load() takes
1598 // an array of unrelated modules, whereas the modules passed to
1599 // using() are related and must all be loaded.
1600 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1601 module
= registry
[modules
[m
]];
1602 if ( module
!== undefined ) {
1603 if ( $.inArray( module
.state
, ['error', 'missing'] ) === -1 ) {
1604 filtered
[filtered
.length
] = modules
[m
];
1609 if ( filtered
.length
=== 0 ) {
1612 // Resolve entire dependency map
1613 filtered
= resolve( filtered
);
1614 // If all modules are ready, nothing to be done
1615 if ( allReady( filtered
) ) {
1618 // If any modules have errors: also quit.
1619 if ( filter( ['error', 'missing'], filtered
).length
) {
1622 // Since some modules are not yet ready, queue up a request.
1623 request( filtered
, undefined, undefined, async
);
1627 * Change the state of one or more modules.
1629 * @param {string|Object} module module name or object of module name/state pairs
1630 * @param {string} state state name
1632 state: function ( module
, state
) {
1635 if ( typeof module
=== 'object' ) {
1636 for ( m
in module
) {
1637 mw
.loader
.state( m
, module
[m
] );
1641 if ( registry
[module
] === undefined ) {
1642 mw
.loader
.register( module
);
1644 if ( $.inArray( state
, ['ready', 'error', 'missing'] ) !== -1
1645 && registry
[module
].state
!== state
) {
1646 // Make sure pending modules depending on this one get executed if their
1647 // dependencies are now fulfilled!
1648 registry
[module
].state
= state
;
1649 handlePending( module
);
1651 registry
[module
].state
= state
;
1656 * Get the version of a module.
1658 * @param {string} module Name of module to get version for
1660 getVersion: function ( module
) {
1661 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1662 return formatVersionNumber( registry
[module
].version
);
1668 * @inheritdoc #getVersion
1669 * @deprecated since 1.18 use #getVersion instead
1671 version: function () {
1672 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1676 * Get the state of a module.
1678 * @param {string} module name of module to get state for
1680 getState: function ( module
) {
1681 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1682 return registry
[module
].state
;
1688 * Get names of all registered modules.
1692 getModuleNames: function () {
1693 return $.map( registry
, function ( i
, key
) {
1699 * Load the `mediawiki.user` module.
1701 * For backwards-compatibility with cached pages from before 2013 where:
1703 * - the `mediawiki.user` module didn't exist yet
1704 * - `mw.user` was still part of mediawiki.js
1705 * - `mw.loader.go` still existed and called after `mw.loader.load()`
1708 mw
.loader
.load( 'mediawiki.user' );
1712 * @inheritdoc mw.inspect#runReports
1715 inspect: function () {
1716 var args
= slice
.call( arguments
);
1717 mw
.loader
.using( 'mediawiki.inspect', function () {
1718 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
1723 * On browsers that implement the localStorage API, the module store serves as a
1724 * smart complement to the browser cache. Unlike the browser cache, the module store
1725 * can slice a concatenated response from ResourceLoader into its constituent
1726 * modules and cache each of them separately, using each module's versioning scheme
1727 * to determine when the cache should be invalidated.
1730 * @class mw.loader.store
1733 // Whether the store is in use on this page.
1736 // The contents of the store, mapping '[module name]@[version]' keys
1737 // to module implementations.
1741 stats
: { hits
: 0, misses
: 0, expired
: 0 },
1744 * Construct a JSON-serializable object representing the content of the store.
1745 * @return {Object} Module store contents.
1747 toJSON: function () {
1748 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
1752 * Get the localStorage key for the entire module store. The key references
1753 * $wgDBname to prevent clashes between wikis which share a common host.
1755 * @return {string} localStorage item key
1757 getStoreKey: function () {
1758 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
1762 * Get a string key on which to vary the module cache.
1763 * @return {string} String of concatenated vary conditions.
1765 getVary: function () {
1767 mw
.config
.get( 'skin' ),
1768 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
1769 mw
.config
.get( 'wgUserLanguage' )
1774 * Get a string key for a specific module. The key format is '[name]@[version]'.
1776 * @param {string} module Module name
1777 * @return {string|null} Module key or null if module does not exist
1779 getModuleKey: function ( module
) {
1780 return typeof registry
[module
] === 'object' ?
1781 ( module
+ '@' + registry
[module
].version
) : null;
1785 * Initialize the store by retrieving it from localStorage and (if successfully
1786 * retrieved) decoding the stored JSON value to a plain object.
1788 * The try / catch block is used for JSON & localStorage feature detection.
1789 * See the in-line documentation for Modernizr's localStorage feature detection
1790 * code for a full account of why we need a try / catch: <http://git.io/4NEwKg>.
1795 if ( mw
.loader
.store
.enabled
!== null ) {
1796 // #init already ran.
1800 if ( !mw
.config
.get( 'wgResourceLoaderStorageEnabled' ) || mw
.config
.get( 'debug' ) ) {
1801 // Disabled by configuration, or because debug mode is set.
1802 mw
.loader
.store
.enabled
= false;
1807 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
1808 // If we get here, localStorage is available; mark enabled.
1809 mw
.loader
.store
.enabled
= true;
1810 data
= JSON
.parse( raw
);
1811 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
1812 mw
.loader
.store
.items
= data
.items
;
1817 if ( raw
=== undefined ) {
1818 mw
.loader
.store
.enabled
= false; // localStorage failed; disable store.
1820 mw
.loader
.store
.update();
1825 * Retrieve a module from the store and update cache hit stats.
1827 * @param {string} module Module name
1828 * @return {string|boolean} Module implementation or false if unavailable
1830 get: function ( module
) {
1833 if ( mw
.loader
.store
.enabled
!== true ) {
1837 key
= mw
.loader
.store
.getModuleKey( module
);
1838 if ( key
in mw
.loader
.store
.items
) {
1839 mw
.loader
.store
.stats
.hits
++;
1840 return mw
.loader
.store
.items
[key
];
1842 mw
.loader
.store
.stats
.misses
++;
1847 * Stringify a module and queue it for storage.
1849 * @param {string} module Module name
1850 * @param {Object} descriptor The module's descriptor as set in the registry
1852 set: function ( module
, descriptor
) {
1855 if ( mw
.loader
.store
.enabled
!== true ) {
1859 key
= mw
.loader
.store
.getModuleKey( module
);
1861 if ( key
in mw
.loader
.store
.items
) {
1862 // Already set; decline to store.
1866 if ( descriptor
.state
!== 'ready' ) {
1867 // Module failed to load; decline to store.
1871 if ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user', 'site' ] ) !== -1 ) {
1872 // Unversioned, private, or site-/user-specific; decline to store.
1876 if ( $.inArray( undefined, [ descriptor
.script
, descriptor
.style
, descriptor
.messages
] ) !== -1 ) {
1877 // Partial descriptor; decline to store.
1883 JSON
.stringify( module
),
1884 typeof descriptor
.script
=== 'function' ?
1885 String( descriptor
.script
) : JSON
.stringify( descriptor
.script
),
1886 JSON
.stringify( descriptor
.style
),
1887 JSON
.stringify( descriptor
.messages
)
1892 mw
.loader
.store
.items
[key
] = 'mw.loader.implement(' + args
.join(',') + ');';
1893 mw
.loader
.store
.update();
1897 * Iterate through the module store, removing any item that does not correspond
1898 * (in name and version) to an item in the module registry.
1900 prune: function () {
1903 if ( mw
.loader
.store
.enabled
!== true ) {
1907 for ( key
in mw
.loader
.store
.items
) {
1908 module
= key
.substring( 0, key
.indexOf( '@' ) );
1909 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
1910 mw
.loader
.store
.stats
.expired
++;
1911 delete mw
.loader
.store
.items
[key
];
1917 * Sync modules to localStorage.
1919 * This function debounces localStorage updates. When called multiple times in
1920 * quick succession, the calls are coalesced into a single update operation.
1921 * This allows us to call #update without having to consider the module load
1922 * queue; the call to localStorage.setItem will be naturally deferred until the
1923 * page is quiescent.
1925 * Because localStorage is shared by all pages with the same origin, if multiple
1926 * pages are loaded with different module sets, the possibility exists that
1927 * modules saved by one page will be clobbered by another. But the impact would
1928 * be minor and the problem would be corrected by subsequent page views.
1930 update
: ( function () {
1935 if ( mw
.loader
.store
.enabled
!== true ) {
1938 mw
.loader
.store
.prune();
1940 data
= JSON
.stringify( mw
.loader
.store
);
1941 localStorage
.setItem( mw
.loader
.store
.getStoreKey(), data
);
1945 return function () {
1946 clearTimeout( timer
);
1947 timer
= setTimeout( flush
, 2000 );
1955 * HTML construction helper functions
1962 * output = Html.element( 'div', {}, new Html.Raw(
1963 * Html.element( 'img', { src: '<' } )
1965 * mw.log( output ); // <div><img src="<"/></div>
1970 html
: ( function () {
1971 function escapeCallback( s
) {
1988 * Escape a string for HTML. Converts special characters to HTML entities.
1989 * @param {string} s The string to escape
1991 escape: function ( s
) {
1992 return s
.replace( /['"<>&]/g, escapeCallback
);
1996 * Create an HTML element string, with safe escaping.
1998 * @param {string} name The tag name.
1999 * @param {Object} attrs An object with members mapping element names to values
2000 * @param {Mixed} contents The contents of the element. May be either:
2001 * - string: The string is escaped.
2002 * - null or undefined: The short closing form is used, e.g. <br/>.
2003 * - this.Raw: The value attribute is included without escaping.
2004 * - this.Cdata: The value attribute is included, and an exception is
2005 * thrown if it contains an illegal ETAGO delimiter.
2006 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
2008 element: function ( name
, attrs
, contents
) {
2009 var v
, attrName
, s
= '<' + name
;
2011 for ( attrName
in attrs
) {
2012 v
= attrs
[attrName
];
2013 // Convert name=true, to name=name
2017 } else if ( v
=== false ) {
2020 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2022 if ( contents
=== undefined || contents
=== null ) {
2029 switch ( typeof contents
) {
2032 s
+= this.escape( contents
);
2036 // Convert to string
2037 s
+= String( contents
);
2040 if ( contents
instanceof this.Raw
) {
2041 // Raw HTML inclusion
2042 s
+= contents
.value
;
2043 } else if ( contents
instanceof this.Cdata
) {
2045 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2046 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2048 s
+= contents
.value
;
2050 throw new Error( 'mw.html.element: Invalid type of contents' );
2053 s
+= '</' + name
+ '>';
2058 * Wrapper object for raw HTML passed to mw.html.element().
2059 * @class mw.html.Raw
2061 Raw: function ( value
) {
2066 * Wrapper object for CDATA element contents passed to mw.html.element()
2067 * @class mw.html.Cdata
2069 Cdata: function ( value
) {
2075 // Skeleton user object. mediawiki.user.js extends this
2082 * Registry and firing of events.
2084 * MediaWiki has various interface components that are extended, enhanced
2085 * or manipulated in some other way by extensions, gadgets and even
2088 * This framework helps streamlining the timing of when these other
2089 * code paths fire their plugins (instead of using document-ready,
2090 * which can and should be limited to firing only once).
2092 * Features like navigating to other wiki pages, previewing an edit
2093 * and editing itself – without a refresh – can then retrigger these
2094 * hooks accordingly to ensure everything still works as expected.
2098 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2099 * mw.hook( 'wikipage.content' ).fire( $content );
2101 * Handlers can be added and fired for arbitrary event names at any time. The same
2102 * event can be fired multiple times. The last run of an event is memorized
2103 * (similar to `$(document).ready` and `$.Deferred().done`).
2104 * This means if an event is fired, and a handler added afterwards, the added
2105 * function will be fired right away with the last given event data.
2107 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2108 * Thus allowing flexible use and optimal maintainability and authority control.
2109 * You can pass around the `add` and/or `fire` method to another piece of code
2110 * without it having to know the event name (or `mw.hook` for that matter).
2112 * var h = mw.hook( 'bar.ready' );
2113 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2115 * Note: Events are documented with an underscore instead of a dot in the event
2116 * name due to jsduck not supporting dots in that position.
2120 hook
: ( function () {
2124 * Create an instance of mw.hook.
2128 * @param {string} name Name of hook.
2131 return function ( name
) {
2132 var list
= lists
[name
] || ( lists
[name
] = $.Callbacks( 'memory' ) );
2136 * Register a hook handler
2137 * @param {Function...} handler Function to bind.
2143 * Unregister a hook handler
2144 * @param {Function...} handler Function to unbind.
2147 remove
: list
.remove
,
2151 * @param {Mixed...} data
2155 return list
.fireWith( null, slice
.call( arguments
) );
2164 // Alias $j to jQuery for backwards compatibility
2167 // Attach to window and globally alias
2168 window
.mw
= window
.mediaWiki
= mw
;
2170 // Auto-register from pre-loaded startup scripts
2171 if ( jQuery
.isFunction( window
.startUp
) ) {
2173 window
.startUp
= undefined;